嗨,我是 Fly,用 Ruby 寫 Chatbot 並挑戰30天分享心得
為確保不會沒靈感
每日含 Ruby 主題文章增加內容
https://github.com/leo424y/clean-code-ruby
Bad:
def create_menu(title, body, button_text, cancellable)
  # ...
end
Good:
def create_menu(title:, body:, button_text:, cancellable:)
  # ...
end
create_menu(
  title: 'Foo',
  body: 'Bar',
  button_text: 'Baz',
  cancellable: true
)
Bad:
def email_clients(clients)
  clients.each do |client|
    client_record = database.lookup(client)
    email(client) if client_record.active?
  end
end
Good:
def email_active_clients(clients)
  clients
    .select(&method(:active_client?))
    .each(&method(:email))
end
def active_client?(client)
  client_record = database.lookup(client)
  client_record.active?
end
Bad:
def add_to_date(date, month)
  # ...
end
date = DateTime.now
# It's hard to to tell from the function name what is added
add_to_date(date, 1)
Good:
def add_month_to_date(date, month)
  # ...
end
date = DateTime.now
add_month_to_date(date, 1)
以便測試
Bad:
def interpret(code)
  regexes = [
    # ...
  ]
  statements = code.split(' ')
  tokens = []
  regexes.each do |regex|
    statements.each do |statement|
      # ...
    end
  end
  ast = []
  tokens.each do |token|
    # lex...
  end
  result = []
  ast.each do |node|
    # result.push(...)
  end
  result
end
Good:
def interpet(code)
  tokens = tokenize(code)
  ast = lex(tokens)
  parse(ast)
end
def tokenize(code)
  regexes = [
    # ...
  ]
  statements = code.split(' ')
  tokens = []
  regexes.each do |regex|
    statements.each do |statement|
      # tokens.push(...)
    end
  end
  tokens
end
def lex(tokens)
  ast = []
  tokens.each do |token|
    # ast.push(...)
  end
  ast
end
def parse(ast)
  result = []
  ast.each do |node|
    # result.push(...)
  end
  result
end
Bad:
def show_developer_list(developers)
  developers.each do |developer|
    data = {
      expected_salary: developer.expected_salary,
      experience: developer.experience,
      github_link: developer.github_link
    }
    render(data)
  end
end
def show_manager_list(managers)
  managers.each do |manager|
    data = {
      expected_salary: manager.expected_salary,
      experience: manager.experience,
      portfolio: manager.mba_projects
    }
    render(data)
  end
end
Good:
def show_employee_list(employees)
  employees.each do |employee|
    data = {
      expected_salary: employee.expected_salary,
      experience: employee.experience
    }
    case employee.type
    when 'manager'
      data[:portfolio] = employee.mba_projects
    when 'developer'
      data[:github_link] = employee.github_link
    end
    render(data)
  end
end
旗標代表會做兩件事以上,一個函數只做一件事
Bad:
def create_file(name, temp)
  if temp
    fs.create("./temp/#{name}")
  else
    fs.create(name)
  end
end
Good:
def create_file(name)
  fs.create(name)
end
def create_temp_file(name)
  create_file("./temp/#{name}")
end